<?php

namespace app\admin\server\music;

use app\admin\common;
use app\admin\model\music\MusicFilesModel;
use app\admin\ServerBase;
use think\db\exception\DbException;
use think\Request;

class MusicFilesServer extends ServerBase
{

    function __construct( Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model=new MusicFilesModel();
    }
    function getList()
    {
        [$page, $limit] = $this->getPage($this->param);
        [$list, $count] = $this->model->getList($this->request, [], '*', $page, $limit);
        $result['data'] = $list;
        $result['count'] = $count;
        $this->getMessageCode('adminMessage.success.select', 2);
        return $result;
    }


    function add()
    {
        $post = $this->request->post();
        try {
            $this->model->saveAll($post['data']);
            $this->getMessageCode('adminMessage.success.insert', 2);
            return true;
        } catch (\Error $error) {
            $this->ERROR = $error->getMessage();
            return false;
        } catch (DbException $dbException) {
            $this->ERROR = $dbException->getMessage();
            return false;
        }
    }

    function export(){
        $ids = $this->request->get('ids');
        $where=[];
        if(!empty($ids)){
            $where['id'] = ['in',$ids];
        }
        [$lists,$count] = $this->model->getList($this->request, $where,'*',1,999999);
        if(empty($lists)){
            $this->getMessageCode('adminMessage.error.select', 1);
            return false;
        }
        $filename=date('Y-m-d H:i',time())."单曲音乐.xlsx";
        $header=[
            '标题',
            '创作者',
            '文件地址',
            '是否展示',
            '金额',
            '原价',
            '播放次数',
            '销量',
            'bmp',
            'key',
            '作家分佣',
        ];
        $data=[];
        foreach ($lists as $val){
            $data[]=[
                'title'=>$val['title'],
                'user_id'=>'',
                'url'=>$val['url'],
                'single_status'=>1,
                'price'=>0,
                'original_price'=>0,
                'play_num'=>0,
                'sale'=>0,
                'bmp'=>'',
                'key'=>'',
                '作家分佣'=>0,
            ];
        }
        $_common_obj=new common();
        return $_common_obj->exportFile($filename,$data,$header);
    }
}